package love.yuanmengrobot.als.business.dao.impl;
/*
 *   @Studio:CHJY · 源梦科技
 *   @Author:COOLIGHT
 *   @Ide:IntelliJ IDEA
 *   @Creation time:2021/5/25 0025 11:07
 */

import love.yuanmengrobot.als.business.dao.StudentGraduationCourseDao;
import love.yuanmengrobot.als.utilPublic.JdbcUtil;
import love.yuanmengrobot.als.utilPublic.SqlString;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.regex.Pattern;

public class StudentGraduationCourseDaoImpl implements StudentGraduationCourseDao {
    /*
     * 显示学号为xxx的要求修的课程
     * @return key课程名称,value 0表示没有选修、1表示修了并且通过了、2表示挂科*/
    @Override
    public HashMap getGraduationCourse(String stuNo) {
        HashMap<String, Integer> course = new   HashMap<String, Integer>();

//        ResultSet rs = DQL.executeQuery(SqlString.selectCourseNameAndScoreSql(stuNo));//查询已修课程情况
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;

//        System.out.println("dao");
        try {
            conn = JdbcUtil.getConnection();
            stmt = conn.createStatement();
            rs = stmt.executeQuery(SqlString.selectCourseNameAndScoreSql(stuNo));//查询已修课程情况

            //已修课程结果处理
            while (rs.next()) {
                String courseName = rs.getString("course_name");
                String score = rs.getString("score");

                if (StudentGraduationCourseDaoImpl.isInteger(score)) {//成绩为数字
                    int scoreInt = Integer.parseInt(score);
                    if (scoreInt >= 60) {
                        course.put(courseName, 1);//通过
                    } else {
                        course.put(courseName, 2);//挂科
                    }

                } else {//成绩为字符串
                    if ("不及格".equals(score) || "旷考".equals(score) || "取消".equals(score) || "不合格".equals(score)) {
                        course.put(courseName, 2);//挂科
                    } else {
                        course.put(courseName, 1);//通过
                    }
                }
            }

//            rs = DQL.executeQuery(SqlString.selectCourseName(stuNo));//查询未修课程情况
            rs =    stmt.executeQuery(SqlString.selectCourseName(stuNo));//查询未修课程情况
            //未修课程结果处理
            while (rs.next()) {
                String courseName = rs.getString("course_name");
                course.putIfAbsent(courseName, 0);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {//回收资源
            JdbcUtil.close(rs,stmt,conn);
        }

        return course;
    }

    /*
     * 判断字符串是否可以转化成数字
     * @return true 可以转成数字,false 不能转成数字
     * @str 需要进行判断的字符串*/
    public static boolean isInteger(String str) {
        Pattern pattern = Pattern.compile("^[-+]?[\\d]*$");
        return pattern.matcher(str).matches();
    }
}
